import httpGlobalConfig from '../common/httpGlobalConfig'

interface App {
  $env: {
    VITE_BASE_API: string
  }
}

interface customConfig {
  toast?: boolean
  catch?: boolean
  auth: boolean
}

interface HttpConfig {
  baseURL: string
  custom?: customConfig
}

interface Response {
  data: {
    code: number
    message: string
    data?: any
  }
  config?: {
    custom?: customConfig
  }
}

export default (app: App) => {
  const { VITE_BASE_API } = app.$env
  uni.$u.http.setConfig((config: HttpConfig) => {
    config.baseURL = VITE_BASE_API // 根域名
    const { custom } = httpGlobalConfig
    config.custom = custom
    return config
  })

  uni.$u.http.interceptors.request.use(
    (config: HttpConfig) => config,
    (config: HttpConfig) => Promise.reject(config)
  )

  uni.$u.http.interceptors.response.use(
    (response: Response) => {
      const { data } = response
      const custom = response.config?.custom

      if (data.code !== 200) {
        if (custom?.toast !== false) {
          uni.$u.toast(data.message)
        }
        if (custom?.catch) {
          return Promise.reject(data)
        }
        return new Promise(() => {})
      }
      return data.data || {}
    },
    (response: Response) => Promise.reject(response)
  )
}
